import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/CheckInventoryRecordApi.dart';
import 'package:flutter_2b_client/components/MyPagedListView.dart';
import 'package:flutter_2b_client/components/showConfirmDialog.dart';
import 'package:flutter_2b_client/utils/DeviceStorageUtils.dart';
import 'package:flutter_2b_client/utils/MobxHooks.dart';
import 'package:flutter_2b_client/utils/ShareUtils.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../apis/MarketDeliveryOrderApi.dart';
import '../components/GoodsListItem.dart';
import '../components/LoadingButton.dart';
import '../store/EmployeeAuthorizationStore.dart';
import '../theme/custom_color.dart';
import '../utils/Page.dart';
import '../utils/PagingUtils.dart';
import '../utils/UIConstant.dart';
import '../utils/local_datetime.dart';

class CheckInventoryRecordDetailPage extends HookWidget {
  final int id;

  const CheckInventoryRecordDetailPage(this.id, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var detailState = useState<CheckInventoryRecordDetail?>(null);
    useEffect(() {
      checkInventoryRecordApi
          .getCheckInventoryRecordDetail(id)
          .then((value) => detailState.value = value);
      return null;
    }, [id]);
    var pagingController =
        usePagingController<Pageable, CheckInventoryRecordItemSummary>(
            firstPageKey: Pageable());
    var totalElementsState = useState(0);
    usePagingControllerListener(
        pagingController,
        (pageable) => checkInventoryRecordApi
                .queryCheckInventoryRecordItems(id, pageable)
                .then((value) {
              totalElementsState.value = value.totalElements;
              return value;
            }),
        (item) => item.goodsId,
        [id]);
    final me = useObservable(
        () => Provider.of<EmployeeAuthorizationStore>(context).me);

    var showSubmitButton = detailState.value?.submittedDateTime == null &&
        me?.hasAuthority("库存_盘点_盘点") == true;
    var showAddButton = (me?.hasAuthority("库存_盘点_盘点") == true &&
        detailState.value?.submittedDateTime == null);

    return Scaffold(
      bottomNavigationBar: showAddButton || showSubmitButton
          ? BottomAppBar(
              child: Row(
                children: [
                  if (showSubmitButton)
                    LoadingButton(
                      onPressed: () async {
                        await showConfirmDialog(
                          context,
                          onConfirm: () async {
                            await checkInventoryRecordApi
                                .submitCheckInventoryRecord(id);
                            detailState.value = detailState.value?.copyWith(
                                submittedDateTime: LocalDateTime.now());
                            if (context.mounted) {
                              context.pop();
                            }
                          },
                          title: "是否确认",
                          content: const Text("提交后将更新库存"),
                        );
                      },
                      child: const Text("提交"),
                    ),
                  if (showAddButton)
                    IconButton(
                        onPressed: () async {
                          var goodsId = await context
                              .push(Uri(path: "/goods", queryParameters: {
                            "editCheckInventoryRecordId": id.toString(),
                          }).toString()) as int?;
                          if (goodsId != null) {
                            var orderItemInOrderSummary =
                                await checkInventoryRecordApi.addGoodsByGoodsId(
                                    id, goodsId);
                            pagingController.itemList =
                                pagingController.itemList?.toList()
                                  ?..add(orderItemInOrderSummary);
                            Fluttertoast.showToast(
                              msg: "添加成功！${orderItemInOrderSummary.name}",
                            );
                          }
                        },
                        icon: const Icon(Icons.add)),
                ],
              ),
            )
          : null,
      floatingActionButton: showAddButton
          ? FloatingActionButton(
              onPressed: () async {
                var barcode = (await context.push(
                  Uri(
                    path: "/scanBarcode",
                    queryParameters: {
                      "checkInventoryRecordId": id.toString(),
                    },
                  ).toString(),
                )) as String?;
                if (barcode != null) {
                  var response = await checkInventoryRecordApi
                      .addGoodsByGoodsBarcode(id, barcode);
                  var list = pagingController.itemList?.toList();
                  list?.add(response);
                  pagingController.itemList = list;
                  totalElementsState.value += 1;

                  Fluttertoast.showToast(
                    msg: "扫描成功！${response.name} ",
                  );
                }
              },
              child: const Icon(Icons.document_scanner),
            )
          : null,
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            expandedHeight: 120,
            pinned: true,
            title: const Text("盘点详情"),
            actions: [
              PopupMenuButton(
                onSelected: (value) async {
                  var bytes =
                      await checkInventoryRecordApi.exportToExcel(id,null);
                  final name = "${detailState.value?.name ?? "卖场盘点"}.xlsx";
                  switch (value) {
                    case 1:
                      if (context.mounted) {
                        await saveFileBytes(context, name, bytes);
                      }
                      break;
                    case 2:
                      if (context.mounted) {
                        await shareExcelFileByBytes(context, bytes, name);
                      }
                      break;
                  }
                },
                itemBuilder: (BuildContext context) =>
                    [...shareAndExportMenuEntries],
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              background: Padding(
                padding: const EdgeInsets.only(left: 16),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "创建时间：${detailState.value?.createdDateTime.format() ?? ""}",
                    ),
                    if (detailState.value?.submittedDateTime != null)
                      Text(
                        "提交时间：${detailState.value?.submittedDateTime?.format() ?? ""}",
                      ),
                    Text(
                      "${totalElementsState.value}个单品",
                    ),
                  ],
                ),
              ),
            ),
          ),
          MyPagedSliverList(
            pagingController: pagingController,
            itemBuilder: (BuildContext context,
                CheckInventoryRecordItemSummary item, int index) {
              return GestureDetector(
                key: Key(item.goodsId.toString()),
                onLongPress: () {
                  showConfirmDeleteGoodsDialog(
                    context,
                    barcode: item.barcode,
                    name: item.name,
                    onConfirm: () async {
                      await checkInventoryRecordApi.deleteCheckInventory(
                          id, item.goodsId);
                      var newItemList = pagingController.itemList
                          ?.where((element) => element.goodsId != item.goodsId)
                          .toList();

                      if (pagingController.nextPageKey != null &&
                          pagingController.itemList != null) {
                        var queryPage = await checkInventoryRecordApi
                            .queryCheckInventoryRecordItems(
                          id,
                          Pageable(
                              page: pagingController.itemList!.length, size: 1),
                        );
                        newItemList?.addAll(queryPage.content);
                      }
                      pagingController.itemList = newItemList;
                      totalElementsState.value -= 1;
                      if (context.mounted) {
                        Navigator.of(context).pop();
                      }
                    },
                  );
                },
                onTap: (){
                  context.push("/goods/${item.goodsId}");
                },
                child: GoodsListItem(
                  onUpdateAmount: (amount, int? unitId) async {
                    final adjustedAmount = max(amount, 0);
                    return checkInventoryRecordApi
                        .updateItemAmount(id, item.goodsId,
                            UpdateItemAmountRequest(amount: adjustedAmount))
                        .then((value) {
                      Fluttertoast.showToast(
                          msg: "修改商品数量成功",
                          backgroundColor: Theme.of(context)
                              .extension<CustomColors>()
                              ?.successContainer,
                          textColor: Theme.of(context)
                              .extension<CustomColors>()
                              ?.onSuccessContainer);
                      final newList = pagingController.itemList!.toList();
                      newList[index] =
                          newList[index].copyWith(amount: adjustedAmount);
                      pagingController.itemList = newList;
                      return null;
                    });
                  },
                  edited: showAddButton || showSubmitButton,
                  name: item.name,
                  inStore: item.inStore,
                  amount: item.amount,
                  barcode: item.barcode,
                  boxSpecification: item.boxSpecification,
                ),
              );
            },
          ),
        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endContained,
    );
  }
}
